package com.example.demo.common;


import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class updDow {
    @Value("${img.path}")
    private String basePath;
    @PostMapping("/upload")
    public R<String> update(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();
        String reName = filename.substring(filename.lastIndexOf("."));
        String path = UUID.randomUUID() +reName;
        File dir = new File(basePath);
        if (!dir.exists()){
            dir.mkdir();
        }
        file.transferTo(new File(basePath+path));
        return R.success(path);
    }
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {

        //定义输入流
        FileInputStream fileInputStream = new FileInputStream(basePath+name);
        //定义输入流
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] bytes = new byte[1024];
        int len ;
        while ((len = fileInputStream.read(bytes)) != -1){
            outputStream.write(bytes,0,len);
            outputStream.flush();
        }
        fileInputStream.close();
        outputStream.close();
    }
}
